package com.yungam.iot_exe.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yungam.common.response.RetDTO;
import com.yungam.iot_exe.bean.Equip;
import com.yungam.iot_exe.bean.IotEquipMenuPermission;
import com.yungam.iot_exe.bean.IotMenu;
import com.yungam.iot_exe.service.EquipService;
import com.yungam.iot_exe.service.IotEquipMenuPermissionService;
import com.yungam.iot_exe.service.IotMenuService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/equip")
public class EquipController {

    @Resource
    private EquipService equipService;
    @Resource
    private IotMenuService menuService;
    @Resource
    private IotEquipMenuPermissionService permissionService;

    /*
    * IOT 边缘端设备菜单查询
    * */
    @GetMapping("/menu")
    public RetDTO<?> getEquipMenu(Integer id) {
        // Step 1: 根据设备 id 寻找菜单类型
        Equip equip = equipService.getById(id);
        if (Objects.isNull(equip) || Objects.isNull(equip.getMenuType())) return RetDTO.data(null);
        String menuType = equip.getMenuType();
        // Step 2: 根据菜单类型寻找设备拥有的菜单项
        QueryWrapper<IotEquipMenuPermission> qw = new QueryWrapper<>();
        qw.eq("menu_type", menuType);
        List<IotEquipMenuPermission> list = permissionService.list(qw);
        List<Integer> menuIdList = list.stream().map(IotEquipMenuPermission::getMenuId)
                                        .collect(Collectors.toList());
        QueryWrapper<IotMenu> menuQw = new QueryWrapper<>();
        menuQw.in("id", menuIdList);
        // 获取菜单列表
        List<IotMenu> menuList = menuService.list(menuQw);
        // 根据权重排序
        menuList.sort((x, y) -> x.getWeight() - y.getWeight());
        return RetDTO.data(menuList);
    }
}
